package com.yupfeg.test.share

import android.os.Handler
import android.os.Looper
import androidx.lifecycle.ViewModel
import com.yupfeg.livedata.EventLiveData
import com.yupfeg.livedata.MutableEventLiveData
import com.yupfeg.livedata.MutableStateLiveData
import com.yupfeg.livedata.StateLiveData

/**
 *
 * @author yuPFeG
 * @date 2021/09/19
 */
class FragmentSharedViewModel : ViewModel(){

    private val mHandler : Handler = Handler(Looper.getMainLooper())

    val singleEvent : EventLiveData<String>
        get() = mSingleEvent
    private val mSingleEvent = MutableEventLiveData<String>()

    val stateEvent : StateLiveData<String>
        get() = mStateEvent
    private val mStateEvent = MutableStateLiveData<String>()

    fun sendSingleEvent(){
        mSingleEvent.value = "fragment shared event"
    }

    fun getTestStateData(){
        Thread().apply {
            //模拟获取数据的流程
            //重置为初始状态如loading
            mStateEvent.resetState()
            mHandler.postAtTime({
                //获取数据成功，赋值数据
                mStateEvent.value = "get test state success"
            },500)
        }
    }

    fun getTestDataError(){
        mStateEvent.setErrorStatus()
    }

    override fun onCleared() {
        super.onCleared()
        mStateEvent.releaseEvent()
    }
}